package hippocrene.core;

import java.util.*;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.SensorManager;
import android.os.IBinder;

import hippocrene.core.HHCompass;
import hippocrene.core.HHGyro;

public class HHCore extends Service{
	
	HHGyro hhGyro;
	HHCompass hhCompass;
	
	Thread mainSensorLoop;
	
	private volatile List<HHModule> fModuleCore = new LinkedList<HHModule>();
	private static SensorManager sensorManager;
	private static short fSensorTimeUpdating=10;
	
	private boolean fIsUpdateRunning;

    @Override
	public void onCreate() {
		try
		{
			sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
			hhGyro = HHGyro.getInstance(sensorManager);
			hhCompass = HHCompass.getInstance();
		} finally {
		}
		
		fModuleCore.add(hhGyro);
		fModuleCore.add(hhCompass);
    }

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
    
	public void startUpdating()
	{
		mainSensorLoop = new Thread(null, sensorThreadUpdating, "Background");
		mainSensorLoop.start();
	}
	
	private Runnable sensorThreadUpdating = new Runnable()
	{
		public void run(){
			long timeInit;
			long timeFinal;
			fIsUpdateRunning=true;
			xInitSensors();
			timeFinal=System.currentTimeMillis();
			while (fIsUpdateRunning==true)
			{
				timeInit=timeFinal;
				xUpdateSensors();
				timeFinal=(int)(System.currentTimeMillis()-timeInit);
				if (fSensorTimeUpdating>timeFinal)
				{
					try {
						Thread.sleep(fSensorTimeUpdating-timeFinal);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			
		}
	};
	
	private void xUpdateSensors() {
		for (HHModule currentModule : fModuleCore) 
    	{
         	currentModule.update();
    	}	
	}	
	

	  /**
	   * xInitI2C, initialize all value from I2C. call one time when I2C is running
	   */
	private void xInitSensors()
	{
		for (HHModule currentModule : fModuleCore) 
	    	{
	         	currentModule.init();
	    	}		
	}


	
}